package com.lvtongka.app.fragment.home

import android.content.Intent
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.location.Location
import android.os.Bundle
import android.text.TextUtils
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.AdapterView
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import com.androideasy.permissions.EasyPermissions
import com.androideasy.permissions.Permission
import com.google.zxing.client.android.MNScanManager
import com.google.zxing.client.android.model.MNScanConfig
import com.lvtongka.app.R
import com.lvtongka.app.base.BaseApplication
import com.lvtongka.app.base.BaseFragment
import com.lvtongka.app.common.widget.SpacesItemDecoration
import com.lvtongka.app.databinding.FragmentHomeBinding
import com.lvtongka.app.common.LocationUtils
import com.lvtongka.app.dialog.AuthorizeDialog
import com.lvtongka.app.dialog.DialogRealName
import com.lvtongka.app.dialog.FuncScanDialog
import com.lvtongka.app.fragment.common.DialogHelper
import com.lvtongka.app.fragment.common.SetPayCallback
import com.lvtongka.app.fragment.home.adapter.HomeArticleAdapter
import com.lvtongka.app.fragment.home.adapter.HomeArticleAdapter.OnItemFlrListener
import com.lvtongka.app.fragment.home.adapter.HomeOnlineAdapter
import com.lvtongka.app.fragment.home.adapter.HomeOfflineAdapter
import com.lvtongka.app.fragment.home.adapter.HomeOfflineGridAdapter
import com.lvtongka.app.fragment.home.bean.HomeMallList
import com.lvtongka.app.fragment.home.bean.OfflineItem
import com.lvtongka.app.fragment.home.bean.OfflineRecord
import com.lvtongka.app.helper.SPHelper
import com.lvtongka.app.helper.SPKConstants
import com.lvtongka.app.http.common.WebConstants
import com.lvtongka.app.okpermission.PermissionLauncher
import com.lvtongka.app.ui.card.BindCardActivity
import com.lvtongka.app.ui.qr.PaymentMerchantActivity
import com.lvtongka.app.ui.recharge.RechargeActivity
import com.lvtongka.app.ui.welfare.WelfareItem
import com.zw.pass.dialog.PayPassDialog

class HomeFragment : BaseFragment<FragmentHomeBinding, HomeViewModel>() {
    private var homeArticleAdapter: HomeArticleAdapter? = null
    private var dialogRealName: DialogRealName? = null
    private var payPassDialog: PayPassDialog? = null
    private var homeOnlineAdapter: HomeOnlineAdapter? = null
    private var homeMallLists : MutableList<HomeMallList> = mutableListOf()
    private var homeMallList: HomeMallList? = null
    private var type = 1
    private var resultSuccess: String? = null

    private var offlineItems = mutableListOf<OfflineItem>()
    private var offlineItem:OfflineItem? = null
    private var homeOfflineAdapter: HomeOfflineAdapter? = null
    private var offlineRecords = mutableListOf<OfflineRecord>()
    private var offlineGridAdapter: HomeOfflineGridAdapter? = null

    private var authorizeDialog: AuthorizeDialog? = null

    override fun initBinding(inflater: LayoutInflater, container: ViewGroup?): FragmentHomeBinding {
        return FragmentHomeBinding.inflate(inflater, container, false)
    }

    override fun initViewModel(): HomeViewModel {
        return ViewModelProvider(this)[HomeViewModel::class.java]
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        isBlack = false
        super.onViewCreated(view, savedInstanceState)
    }

    override fun initEvent() {
        binding.llScan.setOnClickListener {
            if (isFastClick()) {
                return@setOnClickListener
            }
            val isRealName = SPHelper.getBoolean(SPKConstants.IS_REAL_NAME)
            if (!isRealName) {
                DialogHelper.showRealNameHintDialog(context!!) {
                    showRealNameDialog()
                }
                return@setOnClickListener
            } else {
                val isSetPwd = SPHelper.getBoolean(SPKConstants.IS_SET_PWD)
                if (!isSetPwd) {
                    // 未设置支付密码
                    showSetPay()
                    return@setOnClickListener
                }
                val isFuncScan = SPHelper.getBoolean(SPKConstants.IS_FUNC_SCAN)
                if (!isFuncScan) {
                    showFuncScanDialog()
                    return@setOnClickListener
                }
                scan()
            }
        }
        binding.llCoupon.setOnClickListener {
            if (isFastClick()) {
                return@setOnClickListener
            }
            jumpWeb(WebConstants.QUAN_PACKAE)
        }
        binding.llGoRecharge.setOnClickListener {
            if (isFastClick()) {
                return@setOnClickListener
            }
            startActivity(Intent(context, RechargeActivity::class.java))
        }
        binding.llGoTieCard.setOnClickListener {
            if (isFastClick()) {
                return@setOnClickListener
            }
            startActivity(Intent(context, BindCardActivity::class.java))
        }
        binding.llFlqMore.setOnClickListener {
            if (isFastClick()) {
                return@setOnClickListener
            }
            jumpWeb(WebConstants.TACKIT_LIST)
        }
        binding.tvHomeHot.setOnClickListener {
            if (isFastClick()) {
                return@setOnClickListener
            }
            binding.tvHomeHot.setBackgroundResource(R.drawable.bg_btn_pink)
            binding.tvHomeCp.setBackgroundResource(R.drawable.bg_btn_white)
            binding.tvHomeLocal.setBackgroundResource(R.drawable.bg_btn_white)
            binding.tvHomeHot.setTextColor(resources.getColor(R.color.textBD5557))
            binding.tvHomeCp.setTextColor(resources.getColor(R.color.black))
            binding.tvHomeLocal.setTextColor(resources.getColor(R.color.black))
            type = 1
            showLoading()
            viewModel.queryMall(type)
        }
        binding.tvHomeCp.setOnClickListener {
            if (isFastClick()) {
                return@setOnClickListener
            }
            binding.tvHomeHot.setBackgroundResource(R.drawable.bg_btn_white)
            binding.tvHomeCp.setBackgroundResource(R.drawable.bg_btn_pink)
            binding.tvHomeLocal.setBackgroundResource(R.drawable.bg_btn_white)
            binding.tvHomeHot.setTextColor(resources.getColor(R.color.black))
            binding.tvHomeCp.setTextColor(resources.getColor(R.color.textBD5557))
            binding.tvHomeLocal.setTextColor(resources.getColor(R.color.black))
            type = 2
            showLoading()
            viewModel.queryMall(type)
        }
        binding.tvHomeLocal.setOnClickListener {
            if (isFastClick()) {
                return@setOnClickListener
            }
            binding.tvHomeHot.setBackgroundResource(R.drawable.bg_btn_white)
            binding.tvHomeCp.setBackgroundResource(R.drawable.bg_btn_white)
            binding.tvHomeLocal.setBackgroundResource(R.drawable.bg_btn_pink)
            binding.tvHomeHot.setTextColor(resources.getColor(R.color.black))
            binding.tvHomeCp.setTextColor(resources.getColor(R.color.black))
            binding.tvHomeLocal.setTextColor(resources.getColor(R.color.textBD5557))
            type = 3
            showLoading()
            viewModel.queryMall(type)
        }
        binding.tvHomeGm.setOnClickListener {
            if (isFastClick()) {
                return@setOnClickListener
            }
            jumpWeb(WebConstants.ONLINE_BUY_CARD)
        }
        binding.llOnlineMore.setOnClickListener {
            if (isFastClick()) {
                return@setOnClickListener
            }
            jumpWeb(WebConstants.ON_LINE_SHOP)
        }
        binding.llOfflineMore.setOnClickListener {
            if (isFastClick()) {
                return@setOnClickListener
            }
            jumpWeb(WebConstants.BRAND_SHOP_LIST + offlineItem?.id + "&lon="+ BaseApplication.longitude + "&lat=" + BaseApplication.latitude)
        }

        binding.gvOnline.setSelector(ColorDrawable(Color.TRANSPARENT))
        binding.gvOnline.setOnItemClickListener(object : AdapterView.OnItemClickListener {
            override fun onItemClick(
                parent: AdapterView<*>?,
                view: View?,
                position: Int,
                id: Long
            ) {
                if (isFastClick()) {
                    return
                }
                binding.gvOnline.setSelector(ColorDrawable(Color.TRANSPARENT))
                homeMallList = homeMallLists[position]
                viewModel.checkAuthorize(homeMallList!!)
            }
        })


        binding.gvOffline.setSelector(ColorDrawable(Color.TRANSPARENT))
        binding.gvOffline.setOnItemClickListener { _, _, position, _ ->
            if (isFastClick()) {
                return@setOnItemClickListener
            }
            jumpWeb(WebConstants.SHOP_MENDIAN_LIST + offlineRecords[position].id + "&lon="
                    + BaseApplication.longitude + "&lat=" + BaseApplication.latitude + "&name=" + offlineRecords[position].name)
        }
        viewModel.error.observe(this) {
            hideLoading()
            showToast(it)
        }
        viewModel.homeMallPage.observe(this) {
            hideLoading()
            it?.let {
                homeMallLists.clear()
                homeMallLists.addAll(it.list)
            }
            homeOnlineAdapter?.setMallList(homeMallLists)
            if (homeMallLists.isEmpty()) {
                // 显示空
                binding.tvOnlineEmpty.visibility = View.VISIBLE
                binding.gvOnline.visibility = View.GONE
            } else {
                binding.tvOnlineEmpty.visibility = View.GONE
                binding.gvOnline.visibility = View.VISIBLE
            }
        }

        viewModel.welfareItemList.observe(this) {
            hideLoading()
            homeArticleAdapter?.setList(it)
        }

        viewModel.couponCount.observe(this) {
            hideLoading()
        }

        viewModel.realName.observe(this) {
            hideLoading()
            dialogRealName?.dismiss()
            showToast("实名认证成功")
            // 判断是否设置支付密码
            val isSetPwd = SPHelper.getBoolean(SPKConstants.IS_SET_PWD)
            if (!isSetPwd) {
                DialogHelper.showPayHintDialog(context!!) {
                    // 设置支付密码弹窗
                    showSetPay()
                }
            }
        }
        viewModel.setPwd.observe(this) {
            hideLoading()
            showToast("支付密码设置成功")
            DialogHelper.showScanPayDialog(context!!){
                showFuncScanDialog()
            }
        }

        viewModel.scanQrCodeData.observe(this) {
            hideLoading()
            // 识别静态二维码成功
            it?.let {
                startActivity(Intent(context, PaymentMerchantActivity::class.java).apply {
                    putExtra("scanData", it)
                    putExtra("qrCode", resultSuccess)
                })
            }
        }

        viewModel.scanDynamicsQrCodeData.observe(this) {
            hideLoading()
            // 识别动态二维码成功
            it?.let {
                startActivity(Intent(context, PaymentMerchantActivity::class.java).apply {
                    putExtra("scanDynamicsData", it)
                    putExtra("qrCode", resultSuccess)
                })
            }
        }
        viewModel.offlineData.observe(this) {
            hideLoading()
            it?.let {
                offlineItems.clear()
                offlineItems.addAll(it.items)
                offlineItems[0].selectItem = true
            }
            homeOfflineAdapter?.setList(offlineItems)
            offlineItem = offlineItems[0]
            viewModel.queryOffline(offlineItems[0].id)
        }
        viewModel.offlineData2.observe(this) {
            hideLoading()
            it?.let {
                offlineRecords.clear()
                offlineRecords.addAll(it.records)
            }
            offlineGridAdapter?.setOfflineList(offlineRecords)
            if (offlineRecords.isEmpty()) {
                // 显示空
                binding.tvOfflineEmpty.visibility = View.VISIBLE
                binding.gvOffline.visibility = View.GONE
            } else {
                binding.tvOfflineEmpty.visibility = View.GONE
                binding.gvOffline.visibility = View.VISIBLE
            }
        }

        viewModel.onlineData.observe(this) {
            hideLoading()
            if (it.isAuthorized) {
                if (it.selfShop == 1) {
                    jumpWeb(it.redirectUrl)
                } else {
                    jumpWeb(it.redirectUrl, true)
                }
            } else {
                homeMallList?.let {home->
                    showAuthorizeDialog(home)
                }
            }
        }
        viewModel.onlineData2.observe(this) {
            hideLoading()
            if (it.selfShop == 1) {
                jumpWeb(it.redirectUrl)
            } else {
                jumpWeb(it.redirectUrl, true)
            }
        }
        viewModel.openScanPay.observe(this) {
            hideLoading()
            SPHelper.putBoolean(SPKConstants.IS_FUNC_SCAN, true)
            scan()
        }
    }

    override fun initData() {
        val layoutManager = LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false)
        binding.recycleView.layoutManager = layoutManager
        binding.recycleView.addItemDecoration(SpacesItemDecoration(10))
        homeArticleAdapter = HomeArticleAdapter(object : OnItemFlrListener {
            override fun onItemClick(item: WelfareItem) {
                // typeId=typeId&payType=type
                jumpWeb(WebConstants.ON_LINE_QUAN_USE +
                        "typeId=${item.id}&payType=${item.type}")
            }
        })

        binding.recycleView.adapter = homeArticleAdapter
        // 线下好店
        val layoutManager2 = LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false)
        binding.rvOffline.layoutManager = layoutManager2
        homeOfflineAdapter = HomeOfflineAdapter(object : HomeOfflineAdapter.ItemClickListener {
            override fun onItemClick(item: OfflineItem) {
                offlineItem = item
                for (i in offlineItems) {
                    i.selectItem = false
                }
                for (i in offlineItems) {
                    if (TextUtils.equals(i.id, item.id)) {
                        i.selectItem = true
                        break
                    }
                }
                homeOfflineAdapter?.setList(offlineItems)
                // 查询
                showLoading()
                viewModel.queryOffline(item.id)
            }
        })
        binding.rvOffline.adapter = homeOfflineAdapter

        homeOnlineAdapter = HomeOnlineAdapter(context!!)
        binding.gvOnline.adapter = homeOnlineAdapter

        offlineGridAdapter = HomeOfflineGridAdapter(context!!)
        binding.gvOffline.adapter = offlineGridAdapter

        showLocationPermission(false)
        showLoading()
        viewModel.getWelfareList()
        type = 1
        viewModel.queryMall(1)
        // 查询线下好店
        viewModel.queryOfflineClass()
    }

    private fun scan() {
        val listP = listOf(Permission.CAMERA)
        if (EasyPermissions.isGranted(activity!!, listP)) {
            startScan()
        } else {
            PermissionLauncher().with(this)
                .granted {
                    //所有权限都被授予了回调此处
                    startScan()
                }
                .denied {
                    //有权限被拒绝回调此处
                    //rejectPermissionList为被拒绝的权限列表
                    DialogHelper.showPermissionHintDialog(context!!, "相机服务未开启", "请在设置中为本应用开启相机服务以正常使用功能") {
                        PermissionLauncher.openAppDetailSettings(context!!)
                    }
                }
                .request(
                    Permission.CAMERA,
                    getString(R.string.okpermission_camera),
                    getString(R.string.okpermission_camera_rationale)
                )
        }
    }

    private fun startScan() {
        val config = MNScanConfig.Builder().isShowPhotoAlbum(false)
        MNScanManager.startScan(activity!!, config.builder()) { resultCode, data ->
            when (resultCode) {
                MNScanManager.RESULT_SUCCESS -> {
                    resultSuccess =
                        data?.getStringExtra(MNScanManager.INTENT_KEY_RESULT_SUCCESS)
                    resultSuccess?.let {
                        if (it.length > 32) {
                            showLoading("识别中...")
                            viewModel.scanQrCode(it)
                        } else {
                            // 商户动态码
                            showLoading("识别中...")
                            viewModel.scanDynamicsQrCode(it)
                        }
                    }
                }
                MNScanManager.RESULT_FAIL -> {
                    var resultError = data?.getStringExtra(MNScanManager.INTENT_KEY_RESULT_ERROR)
                    showToast(resultError)
                }
                MNScanManager.RESULT_CANCLE -> {
                    showToast("取消扫码")
                }
            }
        }
    }

    // 实名认证弹窗
    private fun showRealNameDialog() {
        dialogRealName = DialogRealName(context!!)
        dialogRealName?.setCancelable(true)
        dialogRealName?.setCanceledOnTouchOutside(true)
        dialogRealName?.setSureListener {
            // 实名认证
            val realName = dialogRealName?.getRealName()
            val realId = dialogRealName?.getRealId()
            if (TextUtils.isEmpty(realName)) {
                showToast("请输入真实姓名")
                return@setSureListener
            }
            if (TextUtils.isEmpty(realId)) {
                showToast("请输入身份证号")
                return@setSureListener
            }
            showLoading("实名认证中...")
            viewModel.realNameAuthentication(realName!!, realId!!)
        }
        dialogRealName?.show()
    }

    private fun showSetPay() {
        // 未设置支付密码
        DialogHelper.showPayHintDialog(context!!) {
            // 设置支付密码弹窗
            DialogHelper.showSetPayFirstDialog(context!!, object : SetPayCallback {
                override fun onSetPayResult(result: String) {
                    // 第二次弹出
                    payPassDialog = DialogHelper.showSetPaySecondDialog(context!!, object : SetPayCallback{
                        override fun onSetPayResult(resultSecond: String) {
                            if (!TextUtils.equals(result, resultSecond)) {
                                showToast("两次输入的密码不一致")
                                return
                            }
                            payPassDialog?.dismiss()
                            showLoading("支付密码设置中...")
                            viewModel.setPayPassword(result)
                        }
                    })
                }
            })
        }
    }

    // 显示位置权限申请
    private fun showLocationPermission(isSkip: Boolean) {
        val listP = listOf(
            Permission.ACCESS_FINE_LOCATION,
            Permission.ACCESS_COARSE_LOCATION
        )
        if (EasyPermissions.isGranted(context!!, listP)) {
            val location: Location? = LocationUtils.getInstance(context!!).showLocation()
            location?.let {
                BaseApplication.latitude = location.latitude.toString()
                BaseApplication.longitude = location.longitude.toString()
            }
        } else {
            PermissionLauncher().with(this)
                .granted {
                    //所有权限都被授予了回调此处
                    val location: Location? =
                        LocationUtils.getInstance(context!!).showLocation()
                    location?.let {
                        BaseApplication.latitude = location.latitude.toString()
                        BaseApplication.longitude = location.longitude.toString()
                    }
                }
                .denied {
                    //有权限被拒绝回调此处
                    //rejectPermissionList为被拒绝的权限列表
                    Log.e("TAG", "拒绝了权限")
                    DialogHelper.showPermissionHintDialog(context!!, "定位服务未开启", "请在设置中为本应用开启定位服务以正常使用功能") {
                        PermissionLauncher.openAppDetailSettings(context!!)
                    }
                }
                .request(
                    arrayOf(Permission.ACCESS_FINE_LOCATION, Permission.ACCESS_COARSE_LOCATION),
                    arrayOf(getString(R.string.okpermission_location)),
                    arrayOf(getString(R.string.okpermission_location_rationale))
                )
        }
    }

    private fun showAuthorizeDialog(mallList: HomeMallList) {
        if (authorizeDialog == null) {
            authorizeDialog = AuthorizeDialog(context!!, R.style.ActionSheetDialogStyle)
            authorizeDialog?.setOnItemClickListener(object :
                AuthorizeDialog.OnConfirmClickListener {
                override fun onConfirm() {
                    authorizeDialog?.hideDialog()
                    showLoading()
                    viewModel.authorize(mallList)
                }
            })
        }
        authorizeDialog?.show()
    }

    private fun showFuncScanDialog() {
        val funcScanDialog = FuncScanDialog(context!!, R.style.ActionSheetDialogStyle)
        funcScanDialog?.setOnItemClickListener(object :
            FuncScanDialog.OnConfirmClickListener {

            override fun onClickConfirm() {
                funcScanDialog?.hideDialog()
                // 开通扫码支付
                DialogHelper.showPayPwdDialog(context!!, object : SetPayCallback {
                    override fun onSetPayResult(result: String) {
                        showLoading("开通中...")
                        viewModel.openScanPay(result)
                    }
                })
            }
        })
        funcScanDialog.show()
    }
}